﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Axe.Extensions;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI;

namespace Axe.Web.Controls
{
    [Serializable]
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class TimeSpanCollection :List<TimeSpan>, IStateManager
    {
        bool tracking = true;

        #region IStateManager Members

        public bool IsTrackingViewState
        {
            get { return tracking; }
        }

        public void LoadViewState(object state)
        {
            this.Clear();
            double[] array = state as double[];
            if (array != null)
            {
                IEnumerable<TimeSpan> items = array.Select<double, TimeSpan>(x => TimeSpan.FromSeconds(x));
                this.AddRange(items);
            }
        }

        public object SaveViewState()
        {
            TimeSpan[] array = this.ToArray();
            IEnumerable<double> items = array.Select<TimeSpan, double>(x => x.TotalSeconds);
            List<double> itms = new List<double>(items);
            return itms.ToArray();
        }

        public void TrackViewState()
        {
            tracking = true;
        }

        #endregion
    }

    public sealed class TimeSpanDropDownList : HardcodedDropDownList
    {
        protected override HardcodedDropDownListEventArgs OnRequestDataItems()
        {
            HardcodedDropDownListEventArgs args = new HardcodedDropDownListEventArgs();

            TimeSpanCollection spans = Spans;
            spans.Sort(delegate(TimeSpan ts1, TimeSpan ts2)
            {
                return TimeSpan.Compare(ts1, ts2);
            });

            foreach (TimeSpan span in Spans)
            {
                ListItem li = new ListItem();
                li.Text = Utility.ToString(span);
                li.Value = span.TotalSeconds.ToString();
                args.BoundItems.Add(li);
            }

            return args;
        }

        [Bindable(true, BindingDirection.TwoWay)]
        public TimeSpan SelectedSpan
        {
            get
            {
                TimeSpan span;
                if (!TimeSpan.TryParse(SelectedValue, out span))
                {
                    span = TimeSpan.FromSeconds(0);
                }
                return span;
            }
            set { SelectedValue = value.TotalSeconds.ToString(); }
        }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public TimeSpanCollection Spans
        {
            get { return ViewState.Get("Spans", new TimeSpanCollection()); }
            set { ViewState["Spans"]=value; }
        }
    }
}
